import {createRouter, createWebHashHistory} from "vue-router"
import {useStore} from "@/store";
import {systemRoutes} from "@/router/systemRoutes";
import {monitorRoutes} from "@/router/monitorRoutes";
import {buildRoutes} from "@/router/buildRoutes";
import {salesRoutes} from "@/router/salesRoutes";
import {customerRoutes} from "@/router/customerRoutes";
import {financeRoutes} from "@/router/financeRoutes";
import {purchaseRoutes} from "@/router/purchaseRoutes";
import {reportRoutes} from "@/router/reportRoutes";

//router
export const useRouter = createRouter({
    history: createWebHashHistory(),
    routes: [
        {
            path: "/",
            name: "index",
            meta: {title: "系统"},
            redirect: '/console',
            component: () => import("@/pages/Index.vue"),
            children: [
                {
                    path: "/console",
                    name: "console",
                    component: () => import("@/pages/indexChild/Console.vue"),
                    meta: {title: "控制台"}
                },
                {
                    path: "/profile",
                    name: "profile",
                    component: () => import("@/pages/indexChild/system/user/profile/index.vue"),
                    meta: {title: "个人中心"}
                },
                {
                    path: "/dict-data/:dictType",
                    name: "dict-data",
                    component: () => import("@/pages/indexChild/system/dict/dictData.vue"),
                    meta: {title: "字典数据"}
                },
                systemRoutes, monitorRoutes, buildRoutes, salesRoutes, customerRoutes, financeRoutes, purchaseRoutes, reportRoutes
            ]
        },
        {
            path: "/login",
            name: "login",
            component: () => import("@/pages/Login.vue")
        },
        {
            path: "/401",
            name: "401",
            component: () => import("@/pages/error/401.vue")
        },
        {
            path: '/:pathMatch(.*)*',
            name: 'NotFound',
            component: () => import('@/pages/error/404.vue')
        },
    ]
})

useRouter.beforeEach((to, from) => {
    const store = useStore()

    let noHas = true

    store.getRouterHistory.forEach(item => {
        // @ts-ignore
        if (item.fullPath === to.fullPath || to.fullPath === '/login') {
            noHas = false
        }
    })

    if (noHas) {
        // @ts-ignore
        to.closable = true
        store.addRouterHistory(to)
    }

    // @ts-ignore
    const isLogin = store.getIsLogin

    if (to.path !== "/login") {
        if (!isLogin) {
            return '/login'
        }
    } else {
        if (isLogin) {
            return '/'
        }
    }
})
